package com.wanho.qz103.hrsaas.sys.contoller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.wanho.qz103.hrsaas.commons.annontations.*;
import com.wanho.qz103.hrsaas.commons.exception.ControllerException;
import com.wanho.qz103.hrsaas.commons.exception.ServiceException;
import com.wanho.qz103.hrsaas.commons.query.Page;
import com.wanho.qz103.hrsaas.commons.util.IDUtils;
import com.wanho.qz103.hrsaas.commons.util.JwtUtils;
import com.wanho.qz103.hrsaas.commons.util.MD5Util;
import com.wanho.qz103.hrsaas.commons.vo.R;
import com.wanho.qz103.hrsaas.commons.vo.TableVO;
import com.wanho.qz103.hrsaas.sys.pojos.Employee;
import com.wanho.qz103.hrsaas.sys.pojos.User;
import com.wanho.qz103.hrsaas.sys.service.UserService;
import com.wanho.qz103.hrsaas.sys.vo.UserInfoVO;
import com.wanho.qz103.hrsaas.sys.vo.UserVO;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@RestController
public class UserController {
    @Autowired
    private UserService userService ;

    /**
     * 保存员工基本信息
     * @param request
     * @return
     * @throws ControllerException
     */
    @PutMapping("/sys/user/{id}")
    public R modify(HttpServletRequest request) throws ControllerException{
        try {
            boolean modifyRs = userService.modify(request.getParameterMap());
            if (modifyRs) {
                return R.success("保存员工基本信息成功！") ;
            }
            return R.fail("保存员工基本信息失败！") ;
        }  catch (ServiceException e) {
            e.printStackTrace();
            throw new ControllerException("保存员工基本信息异常！") ;
        }
    }


    /**
     * 导入  excel 批量插入数据
     * @param request
     * @return
     * @throws ControllerException
     */
    @PostMapping("/sys/user/batch")
    public R importExcel(HttpServletRequest request) throws ControllerException{
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            int count = parameterMap.size()/5 ;
            List<User> userList = new ArrayList<>(count) ;
            for (int i = 0; i < count; i++) {
                String mobile = parameterMap.get(i+"[mobile]")[0] ;
                String username = parameterMap.get(i+"[username]")[0] ;
                String timeOfEntry = parameterMap.get(i+"[timeOfEntry]")[0] ;
                String correctionTime = parameterMap.get(i+"[correctionTime]")[0] ;
                String workNumber = parameterMap.get(i+"[workNumber]")[0] ;
                String userId = IDUtils.randId();
                String salt = UUID.randomUUID().toString();
                String md5 = MD5Util.md5("123456", salt);
                Employee employee = new Employee();
                employee.setUserId(userId);
                employee.setUsername(username);
                employee.setMobile(mobile);
                User user = new User();
                user.setId(userId);
                user.setUsername(username);
                user.setMobile(mobile);
                user.setWorkNumber(workNumber);
                user.setSalt(salt);
                user.setPassword(md5);
                //设置 用户关联 员工
                user.setEmployee(employee);
                // 添加 员工集合中
                userList.add(user) ;
            }
            // 调用业务方法批量导入
            boolean importExcel = userService.importExcel(userList);
            if (importExcel) {
                return R.success("导入员工信息成功！") ;
            }
            return R.fail("导入员工信息失败！") ;
        } catch (ServiceException e) {
            e.printStackTrace();
            return R.fail("导入员工信息异常！！！") ;
        }
    }


    /**
     * 用户列表分页查询
     * @param request
     * @return
     * @throws ControllerException
     */
    @GetMapping("/sys/user")
    public R listPage(HttpServletRequest request) throws ControllerException{
        try {
            String page = request.getParameter("page");
            String size = request.getParameter("size");
            Page page1 = new Page();
            if (StringUtils.isNotEmpty(page)){
                page1.setPage(Long.parseLong(page));
            }
            if (StringUtils.isNotEmpty(size)){
                page1.setSize(Integer.parseInt(size));
            }
            TableVO tableVO = userService.selectPage(page1);
            return R.success("分页查询用户信息成功！",tableVO) ;
        } catch (ServiceException e) {
            e.printStackTrace();
            return R.fail("分页查询用户信息异常！！！") ;
        }
    }


    @GetMapping("/sys/user/simple")
    public R getSimple(HttpServletRequest request) throws ControllerException{
        try {
            List<User> userList = userService.getSimple();
            return R.success("获得用户简单信息成功！",userList) ;
        } catch (ServiceException e) {
            e.printStackTrace();
            return R.fail("根据用户简单信息异常！！！") ;
        }
    }

    @PostMapping("/sys/login")
    public R login(HttpServletRequest request) throws ControllerException{
        try {
            String mobile = request.getParameter("mobile");
            String password = request.getParameter("password");
            System.out.println("用户登录的账号：" + mobile + ",密码:" + password);
            // 调用 登录的业务 方法 获得信息  把用户信息写入jwt token中
//        Map<String,String> map = new HashMap<>();
//        map.put("userId","zhangsan") ;
//        String jwtToken = JwtUtils.createJwtToken(map);
            String token = userService.login(mobile, password);
            if (token==null){
                return R.fail("手机号或密码错误！") ;
            }
            return R.success("登录成功！",token) ;
        } catch (ServiceException e) {
            e.printStackTrace();
            return R.fail("登录失败!") ;
        }
    }

    @PostMapping("/sys/profile")
    public R profile(HttpServletRequest request) throws ControllerException{
        try {
            // 根据 请求头的 token
            String authorization = request.getHeader("Authorization");
            UserVO userVO = userService.getProfile(authorization);
        /*// 去掉 Bearer
        authorization = authorization.substring("Bearer ".length()) ;
        // 调用工具类 进行 获得 用户id
        DecodedJWT tokenInfo = JwtUtils.getTokenInfo(authorization);
        String userId = tokenInfo.getClaim("userId").as(String.class);
        // 调用 业务层 根据 id 查询用户信息
        UserVO userVO = new UserVO();*/
            return R.success("获得用户信息成功！",userVO) ;
        } catch (ServiceException e) {
            e.printStackTrace();
            return R.fail("获得用户信息失败！") ;
        }
    }

    @GetMapping("/sys/user/{id}")
    public R userInfo(HttpServletRequest request) throws ControllerException{
        try {
            //获得路径参数  /api/sys/user/604f764971f93f3ac8f365c2
            String requestURI = request.getRequestURI();
            String[] split = requestURI.split("/");
            String userId = split[split.length-1] ;
            System.out.println("查看详情:" + userId);
            // 调用 业务层 根据 id 查询用户信息
            //UserInfoVO userInfoVO = new UserInfoVO();
            UserInfoVO userInfoVO = userService.getUserInfo(userId);
            return R.success("获得用户基本信息成功！",userInfoVO) ;
        } catch (ServiceException e) {
            e.printStackTrace();
            return R.fail("根据用户id查询详情异常！！！") ;
        }
    }

}
